//
//  NewOrder.m
//  RRBI
//
//  Created by kyjun on 16/4/26.
//
//

#import "NewOrder.h"
#import "Login.h"
#import "Pager.h"
#import "MOrder.h"
#import "OrderCell.h"
#import "OrderHeader.h"
#import "OrderFooter.h"
#import "OrderStoreFooter.h"
#import <DZNEmptyDataSet/UIScrollView+EmptyDataSet.h>
#import "CustomAlertView.h"


@interface NewOrder ()<OrderFooterDeleagte,DZNEmptyDataSetDelegate,DZNEmptyDataSetSource,UIAlertViewDelegate,UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong) NSMutableArray* arrayData;

@property(nonatomic,strong) NSString* cellIdentifier;
@property(nonatomic,strong) NSString* headerIdentifier;
@property(nonatomic,strong) NSString* footerIdentitifer;
@property(nonatomic,strong) NSString* footerStoreIdentifier;

@property(nonatomic,strong) UIAlertView* cancelAlert;
@property(nonatomic,strong) UIAlertView* confirmAlert;
@property(nonatomic,strong) UIAlertView* storeConfirmAlert;
@property(nonatomic,strong) UIAlertView* callAlert;
@property(nonatomic,strong) MOrder* currentOrder;

@end

@implementation NewOrder

//-(instancetype)init{
//    self = [super initWithStyle:UITableViewStyleGrouped];
//    if(self){
//        [self.tabBarItem setImage:[UIImage imageNamedba:@"tab-new-order-default"]];
//        [self.tabBarItem setSelectedImage:[[UIImage imageNamed:@"tab-new-order-enter"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal]];
//        [self.tabBarItem setTitle:@"新订单"];
//        self.tabBarItem.tag=0;
//    }
//    return self;
//}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"點吧商户";
    self.cellIdentifier = @"OrderCell";
    self.headerIdentifier = @"OrderHeader";
    self.footerIdentitifer = @"OrderFooter";
    self.footerStoreIdentifier = @"OrderStoreFooter";
    
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.showsHorizontalScrollIndicator = NO;
    self.tableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.tableView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    [self.view addSubview:self.tableView];
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.bottom.equalTo(self.view);
    }];
    if (@available(iOS 11.0, *))
    {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.estimatedRowHeight = 0;
        self.tableView.estimatedSectionFooterHeight = 0;
        self.tableView.estimatedSectionHeaderHeight = 0;
    }
    
    
    
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
    
    [self.tableView registerClass:[OrderCell class] forCellReuseIdentifier:self.cellIdentifier];
    [self.tableView registerClass:[OrderHeader class] forHeaderFooterViewReuseIdentifier:self.headerIdentifier];
    [self.tableView registerClass:[OrderFooter class] forHeaderFooterViewReuseIdentifier:self.footerIdentitifer];
    [self.tableView registerClass:[OrderStoreFooter class] forHeaderFooterViewReuseIdentifier:self.footerStoreIdentifier];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadData:) name:NotificationRemoteAt object:nil];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    if(!self.Identity.userInfo.isLogin){
        UINavigationController* nav = [[UINavigationController alloc]initWithRootViewController:[[Login alloc]init]];
        [self presentViewController:nav animated:YES completion:nil];
    }else{
        [self refreshDataSource];
    }
}


#pragma mark =====================================================  Data source
-(void)queryData{
     AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
//    NSString *stra = [UserModel sharedInstanced].ru_Id;
    NSDictionary* arg = @{@"ince":@"get_neworder_list",@"sid":[UserModel sharedInstanced].ru_Id};
    [mgr POST:kHost parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        [self.arrayData removeAllObjects];
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            NSArray* array = [responseObject objectForKey:@"data"];
            if(![WMHelper isNULLOrnil:array]){
                [array enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                    MOrder* item = [[MOrder alloc]initWithItem:obj];
                    [self.arrayData addObject:item];
                }];
            }
            [self.tableView reloadData];
        }else{
            [self alertHUD:[responseObject objectForKey:@"msg"]];
        }
        [self.tableView.mj_header endRefreshing];
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        [self alertHUD:@"网络异常"];
        [self.tableView.mj_header endRefreshing];
    }];
    
}

-(void)refreshDataSource{
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        //WJ
        [weakSelf queryData];
    }];
    
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark =====================================================  <UITableViewDataSource>

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.arrayData.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderCell *cell = [tableView dequeueReusableCellWithIdentifier:self.cellIdentifier forIndexPath:indexPath];
    MOrder* empty =self.arrayData[indexPath.section];
    cell.arrayGoods =empty.arrayGoods;
    return cell;
}

#pragma mark =====================================================  <UITableVeiwDelegate>

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MOrder* empty =self.arrayData[indexPath.section];
    return empty.arrayGoods.count*60.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 230.f;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    MOrder* item = self.arrayData[section];
    if([item.emptyID isEqualToString:@"-1"]){
        return 190.f;
    }else{
        if(item.isDelivery){
            return 210.f;
        }else{
            return 180.f;
        }
    }
}

- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    OrderHeader* header =  (OrderHeader*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.headerIdentifier];
    [header loadData:self.arrayData[section] index:section+1];
    return header;
}
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    MOrder* item = self.arrayData[section];
    if([item.emptyID isEqualToString:@"-1"]){
        OrderStoreFooter* footer = (OrderStoreFooter*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.footerStoreIdentifier];
        footer.entity = item;
        footer.delegate = self;
        return footer;
    }else{
        OrderFooter* footer = (OrderFooter*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:self.footerIdentitifer];
        footer.entity = item;
        footer.delegate = self;
        return footer;
    }
}

#pragma mark =====================================================  <OrderFooterDeleagte>
-(void)orderFooterCancel:(MOrder *)item{//商家取消订单
    self.currentOrder = item;

    CustomAlertView *alertView = [[CustomAlertView alloc] initTextViewAlert];
    alertView.textBlock = ^(NSString *textStr) {
        NSLog(@"textStr = %@",textStr);
        [self showHUD];
        AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
        NSDictionary* arg = @{@"ince":@"cancel_shop_order",
                              @"sid":[UserModel sharedInstanced].ru_Id,
                              @"order_id":self.currentOrder.orderID,
                              @"cancel_res":textStr
                              };
        [mgr POST:kHost parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
            [WMHelper outPutJsonString:responseObject];
            NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
            if(flag == 200){
                [self hidHUD:[responseObject objectForKey:@"msg"]];
                [self.tableView.mj_header beginRefreshing];
            }else{
                [self hidHUD:[responseObject objectForKey:@"msg"]];
            }
        } failure:^(NSURLSessionDataTask *task, NSError *error)  {
            [self hidHUD:@"网络异常"];
        }];
        
    };
    
    [alertView showAlertView];
    
}

-(void)orderFooterSend:(MOrder *)item{ //商家接单
    self.currentOrder = item;
//    [self.confirmAlert show];
    
    [self showHUD];
    AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
    NSDictionary* arg = @{@"ince":@"confirm_shop_order",@"sid":[UserModel sharedInstanced].ru_Id,@"order_id":self.currentOrder.orderID};
    [mgr POST:kHost parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        [WMHelper outPutJsonString:responseObject];
        NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
        if(flag == 200){
            [self hidHUD:[responseObject objectForKey:@"msg"]];
            [self.tableView.mj_header beginRefreshing];
        }else{
            [self hidHUD:[responseObject objectForKey:@"msg"]];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error)  {
        
        NSLog( @"%@",error);
        [self hidHUD:@"网络异常"];
        
    }];
}

-(void)orderSended:(MOrder *)item{//商家确认送达
    self.currentOrder = item;
    [self.storeConfirmAlert show];
    
}

-(void)callDelivery:(NSString *)phone{
    self.callAlert =[[UIAlertView alloc] initWithTitle:@"是否拨打电话？" message:phone delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [self.callAlert show];
}
#pragma mark =====================================================  <UIAlertViewDelegate>
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 1){
        if(self.callAlert == alertView){ // 取消接单
            [[UIApplication sharedApplication] openURL:[NSURL URLWithString:[NSString stringWithFormat:@"tel:%@",alertView.message]]];
        }else{
            if (self.cancelAlert == alertView){
                [self showHUD];
                 AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
                NSDictionary* arg = @{@"ince":@"cancel_shop_order",@"sid":[UserModel sharedInstanced].ru_Id,@"order_id":self.currentOrder.orderID};
                [mgr POST:kHost parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                    [WMHelper outPutJsonString:responseObject];
                    NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
                    if(flag == 200){
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                        [self.tableView.mj_header beginRefreshing];
                    }else{
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                    }
                } failure:^(NSURLSessionDataTask *task, NSError *error)  {
                    [self hidHUD:@"网络异常"];
                }];
                
            }else if(self.confirmAlert == alertView){ // 确认接单
                
                [self showHUD];
                 AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
                NSDictionary* arg = @{@"ince":@"confirm_shop_order",@"sid":[UserModel sharedInstanced].ru_Id,@"order_id":self.currentOrder.orderID};
                [mgr POST:kHost parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                    [WMHelper outPutJsonString:responseObject];
                    NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
                    if(flag == 200){
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                        [self.tableView.mj_header beginRefreshing];
                    }else{
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                    }
                } failure:^(NSURLSessionDataTask *task, NSError *error)  {
                    
                    NSLog( @"%@",error);
                    [self hidHUD:@"网络异常"];
                    
                }];
                
            }else if(self.storeConfirmAlert == alertView){
                [self showHUD];
                 AFHTTPSessionManager *mgr=[AFHTTPSessionManager manager];
                NSDictionary* arg = @{@"ince":@"finish_shop_order",@"sid":[UserModel sharedInstanced].ru_Id,@"order_id":self.currentOrder.orderID};
                [mgr POST:kHost parameters:arg progress:nil success:^(NSURLSessionDataTask *task, id responseObject) {
                    [WMHelper outPutJsonString:responseObject];
                    NSInteger flag = [[responseObject objectForKey:@"ret"]integerValue];
                    if(flag == 200){
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                        [self.tableView.mj_header beginRefreshing];
                    }else{
                        [self hidHUD:[responseObject objectForKey:@"msg"]];
                    }
                } failure:^(NSURLSessionDataTask *task, NSError *error)  {
                    [self hidHUD:@"网络异常"];
                }];
            }
        }
    }
}
#pragma mark =====================================================  DZEmptyData 协议实现
- (NSAttributedString *)titleForEmptyDataSet:(UIScrollView *)scrollView
{
    return [[NSAttributedString alloc] initWithString:@"暂无新订单" attributes:@{NSFontAttributeName :[UIFont boldSystemFontOfSize:17.0],NSForegroundColorAttributeName:[UIColor grayColor]}];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView
{
    return roundf(self.tableView.frame.size.height/10.0);
}
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView
{
    return YES;
}

#pragma mark =====================================================  Notification
-(void)reloadData:(NSNotification*)notification{
    [self.tableView.mj_header beginRefreshing];
}

#pragma mark =====================================================  property package
-(NSMutableArray *)arrayData{
    if(!_arrayData){
        _arrayData = [[NSMutableArray alloc]init];
    }
    return _arrayData;
}

-(UIAlertView *)cancelAlert{
    if(!_cancelAlert){
        _cancelAlert = [[UIAlertView alloc] initWithTitle:nil message: @"确认取消订单?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    return _cancelAlert;
}
-(UIAlertView *)confirmAlert{
    if(!_confirmAlert){
        _confirmAlert = [[UIAlertView alloc] initWithTitle:nil message: @"确认发货?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    return _confirmAlert;
}

-(UIAlertView *)storeConfirmAlert{
    if(!_storeConfirmAlert){
        _storeConfirmAlert = [[UIAlertView alloc] initWithTitle:nil message: @"确认送达?" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    }
    return _storeConfirmAlert;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
